import time

from PyQt5.QtCore import *

from Opencv_to_Qpixmap import ThreadOpencvToQpixmap
from Video_Get import ThreadVideoGet


class ThreadEmitImage(QThread):
    my_signal_image = pyqtSignal(list)

    def __init__(self, my_thread_queue_image_done, my_thread_queue_image_read, my_process_queue_image_processing,
                 my_process_queue_image_processed, my_end):
        super(ThreadEmitImage, self).__init__()

        self.my_thread_queue_image_done = my_thread_queue_image_done
        self.my_thread_queue_image_read = my_thread_queue_image_read
        self.my_process_queue_image_processing = my_process_queue_image_processing
        self.my_process_queue_image_processed = my_process_queue_image_processed
        self.my_end = my_end

        self.is_running = True
        self.fps = 30

        self.my_thread_record_screen = ThreadVideoGet(self.my_thread_queue_image_read,
                                                      self.my_process_queue_image_processing,
                                                      self.my_process_queue_image_processed, self.my_end)
        self.my_thread_list = []
        self.my_thread_opencv_to_qpixmap = ThreadOpencvToQpixmap(self.my_thread_queue_image_done,
                                                                 self.my_process_queue_image_processed, self.my_end)

    def run(self) -> None:
        self.my_thread_record_screen.start()
        time.sleep(0.5)
        self.thread_start()
        time.sleep(0.5)
        while self.is_running:
            flag = self.function()
            if not flag:
                time.sleep(0.0015)

    def stop(self):
        self.is_running = False
        self.my_thread_record_screen.stop()
        for my_thread in self.my_thread_list:
            my_thread.stop()

    def function(self):
        if self.my_thread_queue_image_done.empty():
            if not self.my_end.empty():
                self.is_running = False
            return False
        else:
            time.sleep((1 / self.fps) - 0.0015)
            frame, image, data = self.my_thread_queue_image_done.get()
            self.my_signal_image.emit([image])
            return True

    def thread_start(self):
        self.my_thread_list = []
        for i in range(1):
            my_thread_opencv_to_qpixmap = ThreadOpencvToQpixmap(self.my_thread_queue_image_done,
                                                                self.my_process_queue_image_processed, self.my_end)
            self.my_thread_list.append(my_thread_opencv_to_qpixmap)

        time.sleep(0.5)

        for my_thread in self.my_thread_list:
            my_thread.start()
